<template>
    <div class="container">
        <el-card class="table-container">
            <el-table :data="filterTableData" border empty-text="暂无数据">
                <el-table-column type="index" label="序号" sortable align="center" />
                <el-table-column prop="nickname" label="昵称" align="center">
                    <template #default="scope">
                        <el-button type="primary" link>{{ scope.row.nickname }}</el-button>

                    </template>
                </el-table-column>
                <el-table-column prop="avatar" label="头像" align="center">
                    <template #default="scope">
                        <el-avatar :src="scope.row.avatar" />
                    </template>
                </el-table-column>
                <el-table-column prop="root" label="管理员" align="center" sortable>
                    <template #default="scope">
                        <div :style="scope.row.root && { color: 'red' }">
                            <el-tooltip class="box-item" :content="scope.row.root ? '超级用户' : '普通用户'" placement="top">
                                <el-icon>
                                    <UserFilled />
                                </el-icon>
                            </el-tooltip>
                            {{ scope.row.root ? '超级用户' : '普通用户' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="account" label="账号" align="center" />
                <el-table-column label="关注数" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.followings.length }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="粉丝数" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.follower.length }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="password" label="密码" align="center" /> -->
                <!-- <el-table-column prop="id" label="用户id" sortable align="center" width="120px" /> -->
                <el-table-column prop="banned" label="账户状态" align="center" sortable>
                    <template #default="scope">
                        <el-button text :type="scope.row.banned ? 'danger' : 'success'">
                            {{ scope.row.banned ? '已被封' : '正常' }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="240px">
                    <template #header>
                        <el-input v-model="search" size="small" placeholder="搜索标题" />
                    </template>
                    <template #default="scope">
                        <div v-show="!scope.row.root">
                            <el-button type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button type="warning" v-if="!scope.row.banned"
                                @click="banned(scope.$index, scope.row)">封禁</el-button>
                            <el-button type="info" v-else @click="banned(scope.$index, scope.row)">解封</el-button>
                            <el-button type="danger" @click="handleDelAccount(scope.$index, scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="prev, pager, next, jumper, ->, total ,sizes"
                    :page-sizes="['5', '10', '20']" @size-change="sizeChange" @current-change="currentChange"
                    :total="tableInfo.total" small />
            </div>
        </el-card>
    </div>
    <el-dialog v-model="dialogFormVisible" title="个人信息" width="600px">
        <el-form :model="form" ref="updateUserInfoFormRef" :rules="rules">
            <el-form-item label="头像：" :label-width="formLabelWidth">
                <el-upload class="avatar-uploader" :http-request="(options: any) => upload(options, uploadIcon)"
                    :show-file-list="false" :before-upload="beforeAvatarUpload">
                    <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="昵称：" :label-width="formLabelWidth">
                <el-input v-model="form.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别：" :label-width="formLabelWidth">
                <el-select v-model="form.gender" placeholder="--请选择--">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                    <el-option label="保密" value="保密" />
                </el-select>
            </el-form-item>
            <el-form-item label="生日：" :label-width="formLabelWidth">
                <div class="block">
                    <el-date-picker v-model="form.birthday" type="date" placeholder="Pick a date" format="YYYY/MM/DD"
                        :default-value="new Date(2000, 0, 0)" />
                </div>
            </el-form-item>
            <el-form-item label="邮箱：" :label-width="formLabelWidth" prop="email">
                <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话：" :label-width="formLabelWidth" prop="phone">
                <el-input v-model="form.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="地址：" :label-width="formLabelWidth" prop="address">
                <el-input v-model="form.address" autocomplete="off" />
            </el-form-item>
            <el-form-item label="账号：" :label-width="formLabelWidth" prop="account">
                <el-input v-model="form.account" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码：" :label-width="formLabelWidth" prop="password">
                <el-input v-model="form.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="简介：" :label-width="formLabelWidth">
                <el-input v-model="form.introduction" :rows="2" type="textarea" autocomplete="off" />
            </el-form-item>
            <el-form-item label="爱好：" :label-width="formLabelWidth">
                <el-tag v-for="tag in form.hobbies" :key="tag" class="mx-1" closable type="success"
                    :disable-transitions="false" @close="handleClose(tag)">
                    {{ tag }}
                </el-tag>
                <el-input v-if="form.inputVisible" ref="InputRef" v-model="form.inputValue" class="ml-1 w-20" size="small"
                    @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                    + New Tag
                </el-button>
            </el-form-item>
            <el-form-item label="职业：" :label-width="formLabelWidth">
                <el-input v-model="form.profession" autocomplete="off" />
            </el-form-item>
            <el-form-item label="权限：" :label-width="formLabelWidth">
                <el-switch v-model="form.root" class="mb-2"
                    style="--el-switch-on-color:#ff4949 ; --el-switch-off-color:  #13ce66" active-text="超级用户"
                    inactive-text="普通用户" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitSaveUserInfo(updateUserInfoFormRef)">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts' name="account_verified">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { findArticles, updateArticle, findAllCount, editUserInfo, upload, delAccount } from '@/api'
import { ElInput, ElMessage, ElNotification, type FormInstance, type FormRules, type UploadProps, } from 'element-plus';
import { UserFilled, Plus } from '@element-plus/icons-vue'
import { toReactive } from '@vueuse/shared';
import logo from '@/assets/images/logo.jpg'
const tableInfo = reactive({
    users: [],
    pageSize: 10,
    page: 1,
    total: 0
})
onMounted(() => {
    initTableInfo()
})
const initTableInfo = async () => {
    const res = await findAllCount()
    tableInfo.users = res.data.data
    tableInfo.total = res.data.total
}

const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
let form: any = {}
const search = ref('')
const InputRef = ref<InstanceType<typeof ElInput>>()
const updateUserInfoFormRef = ref<FormInstance>()
interface User {
    uuid: string
    nickname: string,
    banned: boolean
}
const rules = reactive<FormRules>({
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },

    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },
        { pattern: /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![!<>#$?@%^&*,]+$)[\da-zA-Z!<>#$?@%^&*,]{6,12}$/, message: '至少包含大小写字母、数字和特殊字符其中两种', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '地址为必填项', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '邮箱为必填项', trigger: 'blur' },
        { type: 'email', message: '格式不对', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { len: 11, message: '手机号码长度不对', trigger: 'blur' }
    ]

})
const filterTableData = computed(() =>
    tableInfo.users.filter(
        (data: any) =>
            !search.value ||
            data.nickname.toLowerCase().includes(search.value.toLowerCase())
    )
)
//编辑用户信息
const handleEdit = async (index: number, row: User) => {
    form = toReactive(JSON.parse(JSON.stringify(row)))
    dialogFormVisible.value = true
    form.hobbies = form.hobbies.map((item: { name: string }) => item.name)
}
//封禁用户
const banned = async (index: number, row: User) => {
    const data = { uuid: row.uuid, banned: !row.banned }
    console.log(data, row.banned);
    try {
        const res = await editUserInfo(data)
        const { nickname, banned } = res.data.data
        ElNotification({
            title: '成功',
            message: `"${nickname}"已${banned ? '被封禁' : '解封'}`,
            type: banned ? 'warning' : 'success'
        })
        initTableInfo()
    } catch (error) {
        ElNotification({
            message: '失败',
            type: 'error'
        })
    }
}
//删除用户
const handleDelAccount = async (index: number, row: User) => {
    const { uuid } = row
    const res = await delAccount(uuid)
    const { code } = res.data
    if (code == 200) {
        ElMessage({
            type: 'success',
            message: res.data.msg
        })
        initTableInfo()
    } else {
        ElMessage({
            type: 'error',
            message: res.data.msg
        })
    }
}

//分页器
const sizeChange = (pageSize: number) => {
    tableInfo.pageSize = pageSize
    initTableInfo()
}
const currentChange = (page: number) => {
    tableInfo.page = page
    initTableInfo()
}
//修改信息提交
const submitSaveUserInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
        if (valid) {
            const res = await editUserInfo(form)
            const { data } = res
            if (data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: data.msg
                })
                //通知仓库更新信息  这里为什么要等待呢  应为需要等待仓库更新完后才再给userInfo赋值
                dialogFormVisible.value = false
                initTableInfo()
            } else {
                ElMessage({
                    type: 'error',
                    message: data.msg
                })
            }
        } else {
            console.log(error);
        }
    })

}

//添加爱好
const handleClose = (tag: string) => {
    form.hobbies.splice(form.hobbies.indexOf(tag), 1)
}
const showInput = () => {
    form.inputVisible = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
const handleInputConfirm = () => {
    if (form.inputValue) {
        form.hobbies.push(form.inputValue)
    }
    form.inputVisible = false
    form.inputValue = ''
}

//上传前规范规格
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const types = ['image/webp', 'image/jpeg', 'image/png']
    if (!types.includes(rawFile.type)) {
        ElMessage.error('图片仅支持webp，jpg，png三种格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

//上传头像
function uploadIcon(res: any) {
    const { data } = res
    if (data.code === 200) {
        ElNotification({
            title: 'Success',
            message: '上传成功',
            type: 'success',
        })
        form.avatar = data.data.imgUrl
    } else {
        ElNotification({
            title: 'Error',
            message: '上传失败',
            type: 'error',
        })
    }
}
</script>
<style scoped lang="scss">
.container {
    width: 100%;

    .table-container {
        width: 100%;

        .pagination {
            margin-top: 10px;
            display: flex;
            justify-content: end;
        }
    }
}

.item {
    margin-top: 10px;
    margin-right: 40px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.mx-1 {
    margin: 0 3px;
}
</style>